package com.matt.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JavaType;
import com.google.common.collect.Lists;
import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.domain.Feeds;
import com.matt.domain.course.Course;
import com.matt.domain.course.CoursePlanClasses;
import com.matt.domain.course.CoursePlanTopic;
import com.matt.domain.nursery.*;
import com.matt.foundation.constant.*;
import com.matt.foundation.ext.aliyun.OSSProcessService;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.push.ClientObject;
import com.matt.foundation.push.PushConstant;
import com.matt.foundation.push.PushMsgVo;
import com.matt.foundation.query.NurseryScheduleCheckQuery;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.ModelUtil;
import com.matt.foundation.utils.PoiUtils;
import com.matt.foundation.vo.children.ChildrenBaseInfoVo;
import com.matt.foundation.vo.children.DailyScheduleVo;
import com.matt.foundation.vo.nursery.*;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.FeedsRepository;
import com.matt.repository.base.ChildrenNativeRepository;
import com.matt.repository.base.CoursePlanClassesNativeRepository;
import com.matt.repository.base.NurseryScheduleCheckNativeRepository;
import com.matt.repository.base.NurseryScheduleNativeRepository;
import com.matt.repository.course.CoursePlanClassesRepository;
import com.matt.repository.course.CoursePlanTopicRepository;
import com.matt.repository.course.CourseRepository;
import com.matt.repository.courseV2.VendorCourseRepository;
import com.matt.repository.nursery.*;
import com.matt.service.*;
import com.matt.service.remoteCall.SsoCallService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.matt.foundation.push.PushConstant.TEACH_NURSERY_SCHEDULE_URL;

;

/**
 * *******************************
 * Created by lch.
 * form com.matt
 * on 2018/11/26
 * *******************************
 */

@Service
@Slf4j
public class NurseryScheduleServiceImpl implements NurseryScheduleService {

	@Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private ClassesService classesService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private OSSProcessService ossProcessService;

    @Value("${aliyun.oss.fileServerPrefix}")
    private String IMG_SERVICE_PREFIX;

	@Autowired
    private CourseAuditService courseAuditService;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    private NurseryScheduleRepository nurseryScheduleRepository;

    @Autowired
    private NurseryScheduleRecordRepository nurseryScheduleRecordRepository;

    @Autowired
    private NurseryScheduleNativeRepository nurseryScheduleNativeRepository;

    @Autowired
    private CoursePlanClassesNativeRepository coursePlanClassesNativeRepository;

    @Autowired
    private NurseryScheduleTempRepository nurseryScheduleTempRepository;

    @Autowired
    private NurseryScheduleTempRecordRepository nurseryScheduleTempRecordRepository;

    @Autowired
    private NurseryScheduleCheckRepository nurseryScheduleCheckRepository;

    @Autowired
    private CoursePlanClassesRepository coursePlanClassesRepository;

    @Autowired
    private NurseryScheduleCheckNativeRepository nurseryScheduleCheckNativeRepository;

    @Autowired
    private NoticeMessageService noticeMessageService;

    @Autowired
    private ChildrenNativeRepository childrenNativeRepository;

    @Autowired
    private FeedsRepository feedsRepository;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private NurseryInstrationRecordRepository nurseryInstrationRecordRepository;

    @Autowired
    private MemVerificationCache cache;

    @Autowired
    private CoursePlanTopicRepository coursePlanTopicRepository;
    @Override
    public List<NurseryScheduleListVo> scheduleList(String areaId, String beginDate, String endDate, int filter) {
        Date beginTime = DateUtil.parseToDate(beginDate);
        Date endTime = DateUtil.parseToDate(endDate);
        if (DateUtil.betweenDay(endTime, beginTime) >= 100 || DateUtil.betweenDay(endTime, beginTime) < 0)
            throw new BusinessException(ErrorCode.DAY_TOO_BIG, "时间范围不对！");
        Calendar calendar = Calendar.getInstance();
        Date tempTime = beginTime;

//        List<WorkDayDTO> workDayList = ssoCallService.getWorkDayList(beginDate, endDate);

        List<NurseryScheduleListVo> nurseryScheduleListVos = new ArrayList<NurseryScheduleListVo>();
        //查询该园区的托班信息
        List<Classes> classesList = classesRepository.findByAreaIdAndCategoryAndDeleted(areaId, ClassesConstant.Category.NURSERY.codeOf(), false);
        //有主题课程的班级
        List<NurseryClassesShortVo> classesShortVoList = nurseryScheduleNativeRepository.getNurseryClassesShortVo(beginTime, endTime, areaId, ClassesConstant.Category.NURSERY.codeOf(), 0);
        //查询这段时间内已经排课的班级
        List<NurserySchedule> nurseryScheduleList = nurseryScheduleNativeRepository.findScheduleBylessonDate(beginDate, endDate, areaId);
        while (tempTime.compareTo(endTime) <= 0) {
            //判断是否是工作日
//            if (workDayList != null && WorkDayDTO.dayIsWorkday(DateUtil.convertStr(tempTime), workDayList)) {
//                NurseryScheduleListVo vo = getNurseryScheduleListVo(classesList, classesShortVoList, nurseryScheduleList, tempTime);
//                nurseryScheduleListVos.add(vo);
//            } else if (workDayList == null && DateUtil.getWorkDay(tempTime)) {
//                NurseryScheduleListVo vo = getNurseryScheduleListVo(classesList, classesShortVoList, nurseryScheduleList, tempTime);
//                nurseryScheduleListVos.add(vo);
//            }

            //循环控制
            calendar.setTime(tempTime);
            calendar.add(calendar.DATE, 1);
            tempTime = calendar.getTime();
        }

        return nurseryScheduleListVos;
    }

    private NurseryScheduleListVo getNurseryScheduleListVo(List<Classes> classesList, List<NurseryClassesShortVo> classesShortVoList, List<NurserySchedule> nurseryScheduleList, Date tempTime) {
        NurseryScheduleListVo vo = new NurseryScheduleListVo();
        vo.setCreated(tempTime);
        //具体
        List<NurseryScheduleVo> scheduleVos = new ArrayList<NurseryScheduleVo>();
        for (Classes classes : classesList) {
            NurseryScheduleVo nurseryScheduleVo = new NurseryScheduleVo();
            nurseryScheduleVo.setClassesId(classes.getId());
            nurseryScheduleVo.setClassesName(classes.getName());
            //判断班级是否主题课
            for (NurseryClassesShortVo nurseryClassesShortVo : classesShortVoList) {
                if (classes.getId().equals(nurseryClassesShortVo.getClassesId()) && DateUtil.sameDate(tempTime, nurseryClassesShortVo.getCourseDate())) {
                    nurseryScheduleVo.setCourseType(NurseryScheduleConstant.CourseType.TOPIC.codeOf());
                    break;
                } else {
                    nurseryScheduleVo.setCourseType(NurseryScheduleConstant.CourseType.NON_TOPIC.codeOf());
                }
            }

            //判断班级是否排课
            for (NurserySchedule nurserySchedule : nurseryScheduleList) {
                if (classes.getId().equals(nurserySchedule.getClassesId()) && DateUtil.sameDate(tempTime, nurserySchedule.getLessonDate())) {
                    nurseryScheduleVo.setId(nurserySchedule.getId());
                    nurseryScheduleVo.setStatus(NurseryScheduleConstant.Status.SCHEDULE.codeOf());
                    nurseryScheduleVo.setLessonDate(nurserySchedule.getLessonDate());
                    break;
                } else {
                    nurseryScheduleVo.setId("");
                    nurseryScheduleVo.setStatus(NurseryScheduleConstant.Status.NON_SCHEDULE.codeOf());
                    nurseryScheduleVo.setLessonDate(null);
                }
            }
            scheduleVos.add(nurseryScheduleVo);
        }
        vo.setScheduleVos(scheduleVos);

        return vo;
    }

    @Override
    public NurseryScheduleDetailVo scheduleDetail(String classesId, String courseDateStr, String nurseryScheduleId) {
        NurseryScheduleVo nurseryScheduleVo = null;
        List<NurseryScheduleRecord> records = null;
        List<CoursePlanClasses> coursePlanClassesList = null;
        if (!"null".equals(nurseryScheduleId) && StringUtils.isNotBlank(nurseryScheduleId)) {
            nurseryScheduleVo = nurseryScheduleNativeRepository.findById(nurseryScheduleId);
            records = nurseryScheduleRecordRepository.findByNurseryScheduleId(nurseryScheduleId);
            coursePlanClassesList = coursePlanClassesNativeRepository.findByCourseDateAndClassesIdAndCategoryOrderByBeginTimeDesc(nurseryScheduleVo.getLessonDate(), nurseryScheduleVo.getClassesId(), ClassesConstant.Category.NURSERY.codeOf());
        } else if (StringUtils.isNotBlank(classesId) && StringUtils.isBlank(nurseryScheduleId)) {
            Classes classes = classesRepository.getOne(classesId);
            nurseryScheduleVo = NurseryScheduleVo.ofDomain(classes, NurseryScheduleConstant.Status.NON_SCHEDULE.codeOf(), null, null);
            records = new ArrayList<NurseryScheduleRecord>();
            NurseryScheduleRecord nurseryScheduleRecord = coursePlanClassesNativeRepository.findByCourseDateAndClassesIdAndCategory(courseDateStr, classes.getId(), ClassesConstant.Category.NURSERY.codeOf());
            if (nurseryScheduleRecord != null) {
                nurseryScheduleRecord.setCategory(1);
                records.add(nurseryScheduleRecord);
            }

            coursePlanClassesList = coursePlanClassesNativeRepository.findByCourseDateAndClassesIdAndCategoryOrderByBeginTimeDesc(DateUtil.parseToDate(courseDateStr), classesId, ClassesConstant.Category.NURSERY.codeOf());
        }
        return NurseryScheduleDetailVo.of(nurseryScheduleVo.getId(), nurseryScheduleVo.getClassesId(), nurseryScheduleVo.getClassesName(),
                nurseryScheduleVo.getLessonDate(), records, coursePlanClassesList.size() > 0 ? coursePlanClassesList.get(0) : null);

    }

    @Override
    public List<NurseryClassesVo> scheduleTeacherClassesList(String staffId, String areaId) {
        List<NurseryClassesVo> list = nurseryScheduleNativeRepository.findByAreaIdAndStaffId(areaId, staffId);
        return list;
    }

    @Override
    public NurseryScheduleDetailVo scheduleTeacherDetail(String classesId, String courseDateStr) {
        return scheduleTeacherDetail(classesId, null, null, courseDateStr);
    }

    @Override
    public NurseryScheduleDetailVo scheduleTeacherDetail(String classesId, String childrenId, String teacherId, String courseDateStr){
        List<NurseryScheduleRecord> records = null;

        NurserySchedule nurserySchedule = null;
        String className = "";

        if (StringUtils.isNotEmpty(classesId)){

            Classes classes = classesRepository.findFirstById(classesId);
            if (classes == null){
                throw new BusinessException(ErrorCode.CLASSES_NOT_EXIST, "班级ID错误");
            }

            className = classes.getName();

            nurserySchedule = nurseryScheduleRepository.findTop1ByClassesIdAndLessonDate(classesId, courseDateStr);

        }else{

            nurserySchedule = nurseryScheduleRepository.findTop1ByTeacherIdAndChildrenIdAndLessonDate(teacherId, childrenId, courseDateStr);
        }

        if (nurserySchedule != null) {

            //给课程追加老师信息
            StaffDTO staff = null;
            if (StringUtils.isNotEmpty(nurserySchedule.getTeacherId())){
                staff = ssoCallService.getStaffDTO(null, nurserySchedule.getTeacherId());
            }

            records = nurseryScheduleRecordRepository.findByNurseryScheduleIdOrderByBeginDateAsc(nurserySchedule.getId());
            for(NurseryScheduleRecord scheduleRecord : records){
                scheduleRecord.setBegin(DateUtil.formatDayToStrByMask(scheduleRecord.getBeginDate(), "HH:mm"));
                scheduleRecord.setEnd(DateUtil.formatDayToStrByMask(scheduleRecord.getEndDate(), "HH:mm"));

                scheduleRecord.setTeacherId(nurserySchedule.getTeacherId());
                if (staff != null){
                    scheduleRecord.setTeacherName(staff.getRealName());
                }
            }

            return NurseryScheduleDetailVo.of_new(nurserySchedule.getId(), nurserySchedule.getClassesId(), className,
                    nurserySchedule.getLessonDate(), records, null);
        }

        return null;
    }

    @Override
    public NurseryScheduleDetailVo scheduleFullChildrenDetail(String childrenId, String courseDateStr){
        List<NurserySchedule> nurserySchedules = nurseryScheduleRepository.findByChildrenIdAndLessonDate(childrenId, courseDateStr);

        if (nurserySchedules.size() == 0){
            return null;
        }

        List<NurseryScheduleRecord> records = new ArrayList<>();
        for (NurserySchedule nurserySchedule : nurserySchedules){

            //给课程追加老师信息
            StaffDTO staff = null;
            if (StringUtils.isNotEmpty(nurserySchedule.getTeacherId())){
                staff = ssoCallService.getStaffDTO(null, nurserySchedule.getTeacherId());
            }

            List<NurseryScheduleRecord> list = nurseryScheduleRecordRepository.findByNurseryScheduleIdOrderByBeginDateAsc(nurserySchedule.getId());

            for(NurseryScheduleRecord scheduleRecord : list){
                scheduleRecord.setBegin(DateUtil.formatDayToStrByMask(scheduleRecord.getBeginDate(), "HH:mm"));
                scheduleRecord.setEnd(DateUtil.formatDayToStrByMask(scheduleRecord.getEndDate(), "HH:mm"));
                scheduleRecord.setTeacherId(nurserySchedule.getTeacherId());
                if (staff != null){
                    scheduleRecord.setTeacherName(staff.getRealName());
                }
            }

            records.addAll(list);
        }
        NurserySchedule nurserySchedule = nurserySchedules.get(0);

        return NurseryScheduleDetailVo.of_new(nurserySchedule.getId(), nurserySchedule.getClassesId(), null,
                nurserySchedule.getLessonDate(), records, null);
    }

    @Override
    public int findCountByClassesIdAndTime(String classesId, String beginDate, String endDate) {
        return nurseryScheduleNativeRepository.findCountByClassesIdAndTime(classesId, beginDate, endDate);
    }

    @Transactional
    @Override
    public NurseryScheduleCheck submitCheck(String areaId, String staffId, String realName, String checkId, String classesId, String beginDate, String endDate) {
        NurseryScheduleCheck nurseryScheduleCheck = null;
        //是否开启托班一日生活流程审核，0是，1否
       //AreaSettingDTO liveSetting = ssoCallService.getAreaSetting(CommonConstant.LIVE_AUDITOR_OPEN_KEY, areaId);
        Map map = courseAuditService.getAuditor(areaId);
        Integer liveIsOpen=Integer.parseInt(map.get("liveIsOpen").toString());
        if (checkId != null && StringUtils.isNotBlank(checkId)) {
            nurseryScheduleCheck = nurseryScheduleCheckRepository.getOne(checkId);
           //nurseryScheduleCheck.setStatus(NurseryScheduleConstant.CheckStatus.WAIT_CHECK.codeOf());
            nurseryScheduleCheck.setUpdateStaffId(staffId);
            nurseryScheduleCheck.setUpdateStaffName(realName);
            nurseryScheduleCheck.setUpdateDate(new Date());
            if(AuditConstant.CLOSE.codeOf()==liveIsOpen){
                nurseryScheduleCheck.setStatus(NurseryScheduleConstant.CheckStatus.PASS_CHECK.codeOf());

       	    }else{
                nurseryScheduleCheck.setStatus(NurseryScheduleConstant.CheckStatus.WAIT_CHECK.codeOf());

       	    }
            //预留
           // if(NurseryScheduleConstant.CheckStatus.PASS_CHECK.codeOf() == status){

        } else {
        	 if(AuditConstant.CLOSE.codeOf()==liveIsOpen){
        		 nurseryScheduleCheck = NurseryScheduleCheck.of(classesId, NurseryScheduleConstant.CheckStatus.PASS_CHECK.codeOf(),
                         DateUtil.parseToDate(beginDate), DateUtil.parseToDate(endDate), staffId, realName, new Date(), areaId);
        	 }else{
        		 nurseryScheduleCheck = NurseryScheduleCheck.of(classesId, NurseryScheduleConstant.CheckStatus.WAIT_CHECK.codeOf(),
                         DateUtil.parseToDate(beginDate), DateUtil.parseToDate(endDate), staffId, realName, new Date(), areaId);
        	 }
        }
        nurseryScheduleCheckRepository.save(nurseryScheduleCheck);

        //消息提醒
     //   noticeMessageService.generateLivePlanAudit(nurseryScheduleCheck.getId());
     //    Map map = courseAuditService.getAuditor(areaId);
        // String liveTeacherId=map.get("liveTeacherId").toString();
        // String liveIsOpen=map.get("liveIsOpen").toString();
//         if(AuditConstant.OPEN.codeOf()==liveIsOpen){
//         	 String liveTeacherId=map.get("liveTeacherId").toString();
//         	 StaffDTO staffDTO = ssoCallService.getStaffDTOById(liveTeacherId);
//
//         	 Classes classes = classesRepository.getOne(classesId);
//             String title = "托班一日生活审核提醒";
//             String content = classes.getName()+"班级的"+beginDate+"-"+endDate+"的一日审核你还未审核。";
//             redPointService.addRemindRedNumByType(areaId, liveTeacherId,staffDTO.getRealName(), RedPointConstant.RED_POINT_SEVEN_DAY_COURSE, 1, title, content,nurseryScheduleCheck.getId(),RoleCodeConstant.ROLE_CODE_TEACHER);
//         }

        return nurseryScheduleCheck;
    }

    @Override
    public NurseryScheduleTemp findByStaffIdAndId(String staffId, String id) {
        return nurseryScheduleTempRepository.findByIdAndStaffId(id, staffId);
    }

    @Transactional
    @Override
    public NurseryScheduleCheck check(String ticket, String checkId, Integer status) {
        StaffDTO staffDTO = cache.getStaff(ticket);
        NurseryScheduleCheck check = nurseryScheduleCheckRepository.getOne(checkId);
        check.setStatus(status);
        check.setCheckStaffId(staffDTO.getId());
        check.setCheckStaffName(staffDTO.getRealName());

        //处理消息提醒
        if (NurseryScheduleConstant.CheckStatus.NON_PASS_CHECK.codeOf() == status)
            noticeMessageService.generateLivePlanRejected(checkId);
        else if (NurseryScheduleConstant.CheckStatus.PASS_CHECK.codeOf() == status) {
            Classes classes = classesRepository.getOne(check.getClassesId());
            noticeMessageService.deleteByLinkIdAndCategory(classes.getId(), NoticeMessageConstant.Category.LIVE_PLAN_AUDIT.codeOf());
        }

        //推送消息处理
        if (NurseryScheduleConstant.CheckStatus.PASS_CHECK.codeOf() == status) {
            pushFeed(check.getClassesId(), staffDTO, check);
        }

        //红点通知处理
        //Map map = courseAuditService.getAuditor(check.getAreaId());
        // List<CoursePlanClasses> coursePlanClassesList = coursePlanClassesRepository.findByAreaIdAndCourseDateBetweenAndClassesId(check.getAreaId(), check.getBeginDate(), check.getEndDate(), check.getClassesId());
//        redPointService.delRemindRedNumByType(check.getAreaId(),staffDTO.getStaffId(), RedPointConstant.RED_POINT_SEVEN_DAY_COURSE, 1, check.getId(),RoleCodeConstant.ROLE_CODE_TEACHER);
        return nurseryScheduleCheckRepository.save(check);
    }

    private boolean pushFeed(String classesId, StaffDTO staffBaseDTO, NurseryScheduleCheck check) {
        List<ChildrenBaseInfoVo> childrenBaseInfoVoList = childrenNativeRepository.getByClassesId(classesId);
        List<PushMsgVo> pushMsgVoList = new ArrayList<>();
        for (ChildrenBaseInfoVo child : childrenBaseInfoVoList) {
            String url = /*techServerUrl +*/ TEACH_NURSERY_SCHEDULE_URL + "?checkId=" + check.getId() + "&childId=" + child.getChildId();
            String content = child.getChildName() + "宝宝" + DateUtil.dateToMd(check.getBeginDate()) + "-" + DateUtil.dateToMd(check.getEndDate()) + "的托班一日流程安排完毕,点击查看详情";
            Feeds vo = Feeds.of(staffBaseDTO.getId(), child.getChildId(), staffBaseDTO.getAreaId(), "", "004",
                    child.getChildName() + "的课程新安排", "", "", "", "", url);
            feedsRepository.save(vo);
            //tag
            List<String> tags = new ArrayList<>();
            tags.add(child.getChildId());
            //extra
            Map<String, String> extras = new HashMap<String, String>();
            extras.put("data", ModelUtil.toJson(ClientObject.of("feed", "", url, vo.getTitle())));
            pushMsgVoList.add(PushMsgVo.of(PushConstant.TEACH_NURSERY_SCHEDULE_TITLE, content, content, PushConstant.APP_SOUND, null, null, tags, extras));
        }

        //TODO:
//        ssoCallService.sendPushByTags(pushMsgVoList, PushConstant.APPKEY, PushConstant.MASTERSECRET);

        return true;
    }

    @Override
    public Page<NurseryScheduleCheckVo> checkPage(NurseryScheduleCheckQuery query) {
        List<NurseryScheduleCheckVo> list = nurseryScheduleCheckNativeRepository.list(query);
        Long count = nurseryScheduleCheckNativeRepository.count(query);
        return new PageImpl<>(list, PageRequest.of(query.getPageNum(), query.getPageSize()), count);
    }

    @Override
    public NurseryScheduleDetailVo checkDetail(String classesId, String courseDate) {
        NurseryScheduleDetailVo vo = null;
        NurseryScheduleVo nurseryScheduleVo = nurseryScheduleNativeRepository.findByClassesIdAndLessonDate(classesId, courseDate);
        NurseryScheduleCheck check = nurseryScheduleCheckNativeRepository.findByClassesIdCourseDate(classesId, courseDate);
        if (nurseryScheduleVo != null) {
            List<NurseryScheduleRecord> records = nurseryScheduleRecordRepository.findByNurseryScheduleId(nurseryScheduleVo.getId());
            List<CoursePlanClasses> coursePlanClassesList = coursePlanClassesNativeRepository.findByCourseDateAndClassesIdAndCategoryOrderByBeginTimeDesc(nurseryScheduleVo.getLessonDate(), nurseryScheduleVo.getClassesId(), ClassesConstant.Category.NURSERY.codeOf());
            vo = NurseryScheduleDetailVo.of(nurseryScheduleVo.getId(), nurseryScheduleVo.getClassesId(), nurseryScheduleVo.getClassesName(),
                    nurseryScheduleVo.getLessonDate(), records, coursePlanClassesList.size() > 0 ? coursePlanClassesList.get(0) : null);
            vo.setCheckId(check.getId());
            vo.setCheckStatus(check.getStatus());
        }
        return vo;
    }

    @Override
    public NurseryScheduleCheck getNurseryScheduleCheck(String classesId, String beginDate, String endDate) {
        return nurseryScheduleCheckRepository.findByClassesIdAndBeginDateAndEndDate(classesId, DateUtil.parseToDate(beginDate), DateUtil.parseToDate(endDate));
    }

//    @Override
//    public WeekNurseryScheduleVo getClassesScheduleList(String checkId, String childId) {
//        NurseryScheduleCheck check = nurseryScheduleCheckRepository.getOne(checkId);
//        if (check == null)
//            throw new BusinessException(ErrorCode.SCHEDULE_CHECK_IS_EXIST, "不存在此条记录");
//        Children children = childrenRepository.getOne(childId);
//
//        AreaDTO areaDTO = ssoCallService.getAreaById(children.getAreaId());
//
//        List<DailyScheduleVo> dailyScheduleVoList = new ArrayList<>();
//
//        //查询 排课记录
//        List<NurseryScheduleRecordVo> recordList = nurseryScheduleCheckNativeRepository.findByClassesIdAndDate(check.getClassesId(), check.getBeginDate(), check.getEndDate());
//        //查询主题课程
//        List<CoursePlanClasses> allCoursePlanClassesList = coursePlanClassesNativeRepository.findByClassesIdAndCategoryOrderByBeginTimeDesc(check.getBeginDate(), check.getEndDate(), check.getClassesId(), ClassesConstant.Category.NURSERY.codeOf());
//
//        Date tempTime = check.getBeginDate();
//        Calendar calendar = Calendar.getInstance();
//        while (tempTime.compareTo(check.getEndDate()) <= 0) {
//            dailyScheduleVoList.add(DailyScheduleVo.of(tempTime, getNurseryScheduleList(recordList, tempTime), getCoursePlanClasses(tempTime, allCoursePlanClassesList)));
//
//            //循环控制
//            calendar.setTime(tempTime);
//            calendar.add(calendar.DATE, 1);
//            tempTime = calendar.getTime();
//        }
//
//        //
//        WeekNurseryScheduleVo vo = WeekNurseryScheduleVo.of(check.getBeginDate(), check.getEndDate(), check.getClassesId(), children.getName(), children.getImgUrl(), areaDTO.getName(), dailyScheduleVoList);
//        return vo;
//    }

    private List<NurseryScheduleRecordVo> getNurseryScheduleList(List<NurseryScheduleRecordVo> recordList, Date tempTime) {
        List<NurseryScheduleRecordVo> nurseryScheduleRecordList = new ArrayList<>();
        nurseryScheduleRecordList = recordList.stream().filter(o -> tempTime.compareTo(o.getLessonDate()) == 0).collect(Collectors.toList());
        return nurseryScheduleRecordList;
    }

    @Autowired
    private VendorCourseRepository vendorCourseRepository;

    @Transactional
    @Override
    public NurserySchedule scheduleAdd(String classesId,  String childrenId, String teacherId, String areaId,  String lessonDate, String scheduleJson) {

        //找到班级
        if (StringUtils.isNotEmpty(classesId)) {
            Classes classes = classesRepository.getOne(classesId);
            if (classes == null){
                throw new BusinessException(ErrorCode.CLASSES_NOT_EXIST, "指定班级不存在!");
            }
        }

        //创建课表
        Date scheduleDate = DateUtil.parseToDate(lessonDate);
        String scheduleDateStr = DateUtil.convertStr(scheduleDate);

        NurserySchedule nurserySchedule = null;

        //找到当前日期当前班级下的所有课表
        List<NurserySchedule> nurseryScheduless = null;

        if (StringUtils.isNotEmpty(classesId)) {
            nurseryScheduless = nurseryScheduleRepository.findByAreaIdAndClassesIdAndLessonDateAndTeacherIdIsNullAndClassesIdIsNull(areaId, classesId, scheduleDate);
        }else{
            nurseryScheduless = nurseryScheduleRepository.findByAreaIdAndChildrenIdAndTeacherIdAndLessonDateAndClassesIdIsNull(areaId, childrenId, teacherId, scheduleDate);
        }

        if(nurseryScheduless.size() == 0){
            nurserySchedule = NurserySchedule.of(null, NurseryScheduleConstant.Status.SCHEDULE.codeOf(), scheduleDate);

            if (StringUtils.isNotEmpty(classesId)) {
                nurserySchedule.setClassesId(classesId);
            }else{
                nurserySchedule.setChildrenId(childrenId);
                nurserySchedule.setTeacherId(teacherId);
            }

            nurserySchedule.setCourseType(NurseryScheduleConstant.CourseType.TOPIC.codeOf());
            nurserySchedule.setAreaId(areaId);
            nurserySchedule = nurseryScheduleRepository.save(nurserySchedule);
        }else{
            nurserySchedule = nurseryScheduless.get(0);
            //是不是需要删除掉其他的课表？
        }

        //找到课表下现有的课程排课计划， 并全部清除
        List<CoursePlanClasses> coursePlanClassesList =
                coursePlanClassesNativeRepository.findByCourseDateAndClassesIdOrderByBeginTimeDesc(nurserySchedule.getLessonDate(), nurserySchedule.getClassesId());

        if (coursePlanClassesList != null && coursePlanClassesList.size() > 0) {
            coursePlanClassesRepository.deleteAll(coursePlanClassesList);
        }

        List<NurseryScheduleRecord> recordList = JSON.parseArray(scheduleJson, NurseryScheduleRecord.class);

        for (NurseryScheduleRecord record : recordList) {

            record.setNurseryScheduleId(nurserySchedule.getId());

            record.setBeginDate(DateUtil.parseToDayHourM( scheduleDateStr + " " + record.getBegin()));
            record.setEndDate(DateUtil.parseToDayHourM(scheduleDateStr + " " + record.getEnd()));

            nurseryScheduleRecordRepository.save(record);

        }

        return nurserySchedule;
    }

    @Transactional
    @Override
    public NurserySchedule scheduleUpdate(String nurseryScheduleId,String areaId, String scheduleJson) {
    	NurserySchedule nurserySchedule = nurseryScheduleRepository.getOne(nurseryScheduleId);


    	//通过班级ID获取班级信息
        Classes classes = classesRepository.getOne(nurserySchedule.getClassesId());
        if (StringUtils.isNotBlank(nurserySchedule.getId())) {
          	//获取当天已排主题课
      		List<CoursePlanClasses> coursePlanClassesList=coursePlanClassesNativeRepository.findByCourseDateAndClassesIdOrderByBeginTimeDesc(nurserySchedule.getLessonDate(), nurserySchedule.getClassesId());
      	   for (CoursePlanClasses coursePlanClasses : coursePlanClassesList) {
      			coursePlanClassesRepository.deleteById(coursePlanClasses.getId());
      		}
        	JavaType javaType = ModelUtil.objectMapper.getTypeFactory().constructParametricType(ArrayList.class, NurseryScheduleRecord.class);
            try {
                List<NurseryScheduleRecord> nurseryScheduleRecordList = ModelUtil.objectMapper.readValue(scheduleJson, javaType);
                //删除之前的历史记录
                int i = nurseryScheduleRecordRepository.deleteByNurseryScheduleId(nurseryScheduleId);
                for (NurseryScheduleRecord nurseryScheduleRecord : nurseryScheduleRecordList) {
                    nurseryScheduleRecord.setNurseryScheduleId(nurserySchedule.getId());
                    nurseryScheduleRecord.setBeginDate(DateUtil.parseToDayHourM(DateUtil.convertStr(nurserySchedule.getLessonDate()) + " " + nurseryScheduleRecord.getBegin()));
                    nurseryScheduleRecord.setEndDate(DateUtil.parseToDayHourM(DateUtil.convertStr(nurserySchedule.getLessonDate()) + " " + nurseryScheduleRecord.getEnd()));
                    nurseryScheduleRecordRepository.save(nurseryScheduleRecord);
                    if(nurseryScheduleRecord.getCategory()!=0){
                        //

                        Course course = courseRepository.findCourseById(nurseryScheduleRecord.getResObj());
                        CoursePlanClasses coursePlanClasses=new CoursePlanClasses();
                  		    coursePlanClasses.setAreaId(classes.getAreaId());
                  			coursePlanClasses.setBeginCourseTeacherId("");
                  			coursePlanClasses.setBeginCourseTime(null);

                  			//coursePlanClasses.setBeginTime(DateUtil.parseToDayHourMS(nurseryScheduleRecord.getBeginDate()));
                  			coursePlanClasses.setBeginTime(DateUtil.parseToDayHourM(DateUtil.convertStr(nurserySchedule.getLessonDate()) + " " + nurseryScheduleRecord.getBegin()));
                  			coursePlanClasses.setEndTime(DateUtil.parseToDayHourM(DateUtil.convertStr(nurserySchedule.getLessonDate()) + " " + nurseryScheduleRecord.getEnd()));
                            coursePlanClasses.setCategory(classes.getCategory());//托班
                  		    //CourseConstant.Category.NURSERY.codeOf();
                  			coursePlanClasses.setClassesId(classes.getId());
                  			coursePlanClasses.setCourseDate(nurserySchedule.getLessonDate());
                            coursePlanClasses.setCourseId(nurseryScheduleRecord.getResObj());
                            coursePlanClasses.setCourseName(nurseryScheduleRecord.getActivityContent());

                        //coursePlanClasses.setCoursePlanTopicId(coursePlanTopic.getId());
                  			coursePlanClasses.setCourseStatus(0);
                        if(course!=null){
                            coursePlanClasses.setCourseType(course.getType());
                            coursePlanClasses.setTypeName(course.getTypeName());
                        }else{
                            coursePlanClasses.setCourseType(1);
                        }

                        //coursePlanClasses.setCourseType(newCourse.getType());
                  			coursePlanClasses.setCreated(new Date());
                  			coursePlanClasses.setDeleted(false);
                  			coursePlanClasses.setPrepareStatus(0);
                  			//coursePlanClasses.setTypeName(newCourse.getTypeName());
                  			String coursePlanClassesId=UUID.randomUUID().toString().replaceAll("-", "");
                  			coursePlanClasses.setId(coursePlanClassesId);
                  			List<CoursePlanTopic> coursePlanTopicList =	coursePlanTopicRepository.findByCourseId(nurseryScheduleRecord.getResObj());
                  			if(Objects.nonNull(coursePlanTopicList)&&coursePlanTopicList.size()>0){
                  			    coursePlanClasses.setCoursePlanTopicId(coursePlanTopicList.get(0).getId());
                  			}
                  			CoursePlanClasses newCoursePlanClasses=coursePlanClassesRepository.save(coursePlanClasses);
                  			//如果是主题课程 新增观测点
                  			if(nurseryScheduleRecord.getCategory()==1){
              			     if(Objects.nonNull(coursePlanTopicList)){
              				     //新增课程观测点

              			       }
                  			}
                  			//如果是康轩主课程新增观测点

                     	   }
                   }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("json 转集合对象异常");
            }
        }
        nurserySchedule.setAreaId(areaId);
        nurseryScheduleRepository.save(nurserySchedule);
        return nurserySchedule;
    }

    @Transactional
    @Override
    public NurseryScheduleTemp scheduleTempAdd(String areaId, String staffId, String name, String lessonDate, String scheduleJson) {
        NurseryScheduleTemp temp = nurseryScheduleTempRepository.save(NurseryScheduleTemp.of(name, DateUtil.parseToDate(lessonDate), areaId, staffId));
        if (StringUtils.isNotBlank(temp.getId())) {
            JavaType javaType = ModelUtil.objectMapper.getTypeFactory().constructParametricType(ArrayList.class, NurseryScheduleTempRecord.class);
            try {
                List<NurseryScheduleTempRecord> nurseryScheduleRecordList = ModelUtil.objectMapper.readValue(scheduleJson, javaType);
                for (NurseryScheduleTempRecord record : nurseryScheduleRecordList) {
                    nurseryScheduleTempRecordRepository.save(NurseryScheduleTempRecord.ofDomain(temp, record));
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("json 转集合对象异常");
            }
        }
        return temp;
    }

    @Override
    public List<NurseryScheduleTempListVo> loadTemp(String areaId,String staffId) {
        List<NurseryScheduleTempListVo> nurseryScheduleTempListVos = new ArrayList<>();
        List<NurseryScheduleTemp> temps = nurseryScheduleTempRepository.findByAreaId(areaId);
        List<NurseryScheduleTemp> ownList = temps.stream().filter(temp -> staffId.equals(temp.getStaffId())).collect(Collectors.toList());
        List<NurseryScheduleTemp> otherList = temps.stream().filter(temp -> !staffId.equals(temp.getStaffId())).collect(Collectors.toList());
        List<NurseryScheduleTemp> sortedTemps = new ArrayList<NurseryScheduleTemp>();
        if (ownList.size() > 0)
            sortedTemps.addAll(ownList);
        if (otherList.size() > 0)
            sortedTemps.addAll(otherList);
        for (NurseryScheduleTemp temp : sortedTemps) {
            List<NurseryScheduleTempRecord> tempRecords = nurseryScheduleTempRecordRepository.findByNurseryScheduleTempId(temp.getId());
            nurseryScheduleTempListVos.add(NurseryScheduleTempListVo.of(temp, tempRecords));
        }
        return nurseryScheduleTempListVos;
    }

    @Transactional
    @Override
    public boolean deleteScheduleRecord(String id) {
        nurseryScheduleRecordRepository.deleteById(id);
        return true;
    }

    @Transactional
    @Override
    public boolean deleteTemp(String id) {
        try {
            int i = nurseryScheduleTempRecordRepository.deleteByNurseryScheduleTempId(id);
            nurseryScheduleTempRepository.deleteById(id);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.DELETE_ERROR, "删除模版失败！");
        }
        return true;
    }

    @Transactional
    @Override
    public void updateNurseryScheduleRecord(String areaId, Date courseDate, String classesId, String coursePlanClassId) {
        try {
            List<NurserySchedule> nurserySchedule = nurseryScheduleRepository.findByAreaIdAndClassesIdAndLessonDateAndTeacherIdIsNullAndClassesIdIsNull(areaId, classesId, courseDate);
            if (Objects.isNull(nurserySchedule))
                return;
            nurseryScheduleRecordRepository.deleteByNurseryScheduleIdAndCategory(nurserySchedule.get(0).getId(), NurseryScheduleConstant.CourseType.TOPIC.codeOf());
            CoursePlanClasses coursePlanClasses = coursePlanClassesRepository.getOne(coursePlanClassId);
            NurseryScheduleRecord recordVo = new NurseryScheduleRecord();
            recordVo.setNurseryScheduleId(nurserySchedule.get(0).getId());
            recordVo.setCategory(NurseryScheduleConstant.CourseType.TOPIC.codeOf());
            recordVo.setBeginDate(coursePlanClasses.getBeginTime());
            recordVo.setEndDate(coursePlanClasses.getEndTime());
            recordVo.setActivityContent(coursePlanClasses.getCourseName());
            nurseryScheduleRecordRepository.save(recordVo);
        } catch (Exception e) {
            log.info("修改托班排课信息失败！");
        }
    }

    @Override
    public PrintScheduleVo getPrintDaySchedule(StaffDTO staff, AreaDTO area, String nurseryScheduleId) {
        List<Object[]> info = nurseryScheduleNativeRepository.getAreaIdAndClassesName(nurseryScheduleId);

        if (info.isEmpty() || info.size() == 0)
            throw new BusinessException(ErrorCode.NURSERY_SCHEDULE_IS_BLANK, "不存在记录");

        List<CoursePlanClasses> coursePlanClassesList = null;

        if (info.get(0)[2] != null && StringUtils.isNotBlank(info.get(0)[3].toString()))
            coursePlanClassesList = coursePlanClassesNativeRepository.findByCourseDateAndClassesIdAndCategoryOrderByBeginTimeDesc((Date) info.get(0)[2], info.get(0)[3].toString(), ClassesConstant.Category.NURSERY.codeOf());
        List<NurseryScheduleRecord> nurseryScheduleRecordList = nurseryScheduleRecordRepository.findByNurseryScheduleIdOrderByBeginDateAsc(nurseryScheduleId);

        return PrintScheduleVo.of(info.get(0)[0].toString(), area.getName(), info.get(0)[2] == null ? null : (Date) info.get(0)[2], nurseryScheduleRecordList, coursePlanClassesList);
    }

    @Override
    public PrintWeekScheduleVo getPrintWeekSchedule(AreaDTO area, String checkId, Integer type) {
        List<Object[]> info = nurseryScheduleCheckNativeRepository.getAreaIdAndClassesName(checkId);
        if (info.isEmpty() || info.size() == 0)
            throw new BusinessException(ErrorCode.NURSERY_SCHEDULE_IS_BLANK, "不存在记录");

        Date beginDate = (Date) info.get(0)[3];
        Date endDate = (Date) info.get(0)[4];
        String classesId = info.get(0)[2].toString();
        Date tempTime = beginDate;
        Calendar calendar = Calendar.getInstance();

        if (PrintConstant.Type.SAME.codeOf() == type) {
            if (!judgeCourseTimeSame(classesId, beginDate, endDate))
                throw new BusinessException(ErrorCode.SCHEDULE_IS_NOT_SAME, "周排课时间不一致，不能一起打印");
        }

        List<DailyScheduleVo> dailyScheduleVoList = new ArrayList<>();

        //查询排课记录
        List<NurseryScheduleRecordVo> recordList = nurseryScheduleCheckNativeRepository.findByClassesIdAndDate(classesId, beginDate, endDate);
        //查询beginDate - endDate 的主题课程
        List<CoursePlanClasses> allCoursePlanClassesList = coursePlanClassesNativeRepository.findByClassesIdAndCategoryOrderByBeginTimeDesc(beginDate, endDate, classesId, ClassesConstant.Category.NURSERY.codeOf());

        while (tempTime.compareTo(endDate) <= 0) {

            CoursePlanClasses coursePlanClasses = getCoursePlanClasses(tempTime, allCoursePlanClassesList);
            dailyScheduleVoList.add(DailyScheduleVo.of(tempTime, getNurseryScheduleList(recordList, tempTime), coursePlanClasses));

            //循环控制
            calendar.setTime(tempTime);
            calendar.add(calendar.DATE, 1);
            tempTime = calendar.getTime();
        }
        PrintWeekScheduleVo vo = PrintWeekScheduleVo.of(info.get(0)[0].toString(), area.getName(), dailyScheduleVoList);
        return vo;
    }

    private CoursePlanClasses getCoursePlanClasses(Date tempTime, List<CoursePlanClasses> allCoursePlanClassesList) {
        for (CoursePlanClasses vo : allCoursePlanClassesList) {
            if (tempTime.compareTo(vo.getCourseDate()) == 0) {
                return vo;
            }
        }
        return null;
    }


    @Override
    public CheckNurseryScheduleVo checkDetailWeek(AreaDTO area, String checkId) {
        //默认按照时间相同
        List<Object[]> info = nurseryScheduleCheckNativeRepository.getAreaIdAndClassesName(checkId);
        if (info.isEmpty() || info.size() == 0)
            throw new BusinessException(ErrorCode.NURSERY_SCHEDULE_IS_BLANK, "不存在记录");

        Date beginDate = (Date) info.get(0)[3];
        Date endDate = (Date) info.get(0)[4];
        String classesId = info.get(0)[2].toString();
        Date tempTime = beginDate;
        Calendar calendar = Calendar.getInstance();


        boolean same = judgeCourseTimeSame(classesId, beginDate, endDate);
        List<DailyScheduleVo> dailyScheduleVoList = new ArrayList<>();

        //查询排课记录
        List<NurseryScheduleRecordVo> recordList = nurseryScheduleCheckNativeRepository.findByClassesIdAndDate(classesId, beginDate, endDate);
        //查询beginDate - endDate 的主题课程
        List<CoursePlanClasses> allCoursePlanClassesList = coursePlanClassesNativeRepository.findByClassesIdAndCategoryOrderByBeginTimeDesc(beginDate,
                endDate, classesId, ClassesConstant.Category.NURSERY.codeOf());

        while (tempTime.compareTo(endDate) <= 0) {

            CoursePlanClasses coursePlanClasses = getCoursePlanClasses(tempTime, allCoursePlanClassesList);
            dailyScheduleVoList.add(DailyScheduleVo.of(tempTime, getNurseryScheduleList(recordList, tempTime), coursePlanClasses));

            //循环控制
            calendar.setTime(tempTime);
            calendar.add(calendar.DATE, 1);
            tempTime = calendar.getTime();
        }
        CheckNurseryScheduleVo vo = CheckNurseryScheduleVo.of(info.get(0)[0].toString(), area.getName(), dailyScheduleVoList, same,
                beginDate, endDate, Integer.parseInt(info.get(0)[5].toString()), (Date) info.get(0)[6], info.get(0)[7].toString());
        return vo;
    }

    //判断班级排课时间是否相同
    private boolean judgeCourseTimeSame(String classesId, Date beginDate, Date endDate) {
        List<BigInteger> beginDateInfo = nurseryScheduleCheckNativeRepository.getBeginInfo(classesId, beginDate, endDate);
        List<BigInteger> endDateInfo = nurseryScheduleCheckNativeRepository.getEndInfo(classesId, beginDate, endDate);
        List<BigInteger> nurseryInfo = nurseryScheduleCheckNativeRepository.getNurseryInfo(classesId, beginDate, endDate);

        if (beginDateInfo.size() != endDateInfo.size())
            return false;

        for (int i = 0; i < beginDateInfo.size(); i++) {
            if (beginDateInfo.get(i) != nurseryInfo.get(0))
                return false;
            if (endDateInfo.get(i) != nurseryInfo.get(0))
                return false;
        }
        return true;
    }
    @Transactional
    @Override
    public NurserySchedule nurseryScheduleRecordAdd(String areaId, String classesId, Date lessonDay) {
        List<NurserySchedule> nurseryS = nurseryScheduleRepository.findByAreaIdAndClassesIdAndLessonDate(areaId, classesId, lessonDay);
    	//判断当天是否已排课，如排课删除相关数据
        if(nurseryS.size()>0){
    		nurseryScheduleRecordRepository.deleteByNurseryScheduleId(nurseryS.get(0).getId());
    		nurseryScheduleRepository.deleteById(nurseryS.get(0).getId());
    		 //throw new BusinessException(ErrorCode.COURSE_SCHEDULE_ERROR, "当天已排课");
    	}
        NurserySchedule nurserySchedule = NurserySchedule.of(classesId, NurseryScheduleConstant.Status.SCHEDULE.codeOf(), lessonDay);
        nurserySchedule.setCourseType(NurseryScheduleConstant.CourseType.TOPIC.codeOf());
        nurserySchedule.setAreaId(areaId);
        nurseryScheduleRepository.save(nurserySchedule);

        //通过班级ID获取班级信息
        Classes classes = classesRepository.getOne(classesId);
        //计算入园月龄
        Instant instant = lessonDay.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = instant.atZone(zoneId).toLocalDate();

        LocalDate currentDate = localDate.plusMonths(classes.getBeginMonth());
        LocalDate createdDate = LocalDate.parse( DateUtil.convertStr(classes.getCreated()));
        Integer diffMonth = Period.between(createdDate,currentDate).getMonths();
        //计算入园天数
        Integer diffDay = Period.between(createdDate,currentDate).getDays();

        log.info("diffMonth", diffMonth);
        log.info("diffDay", diffDay);

        //获取班级一日生活排课模板信息
        List<NurseryInstructionRecord> nurseryInstructionRecord = nurseryInstrationRecordRepository.findAllByTargetObjectId(classes.getTargetObjectId());
        List<NurseryScheduleRecord> nurseryScheduleList = Lists.newArrayList();

        //保存一日活动安排记录
        for(int i = 0 ; i < nurseryInstructionRecord.size() ; i++){
            NurseryInstructionRecord instructionRecord = nurseryInstructionRecord.get(i);

            //创建一个托班日程表对象
        	NurseryScheduleRecord nurseryScheduleRecord = new NurseryScheduleRecord();
        	nurseryScheduleRecord.setBeginDate(DateUtil.parseLocalDateTimeToDate(localDate, instructionRecord.getBeginDate()));
    		nurseryScheduleRecord.setEndDate(DateUtil.parseLocalDateTimeToDate(localDate, instructionRecord.getEndDate()));
    		nurseryScheduleRecord.setCategory(instructionRecord.getCategory());
    		nurseryScheduleRecord.setNurseryScheduleId(nurserySchedule.getId());

    		if(instructionRecord.getCategory() == 1) {
                String lessonDayStr = DateUtil.formatDayToStr(lessonDay);

                //获取当天主题信息
                List<CoursePlanTopic> coursePlanTopicList = coursePlanTopicRepository.findByCourseDate(DateUtil.parseToDay(lessonDayStr));

                //获取当天已排课主题课,并且清除掉排课表记录
                List<CoursePlanClasses> coursePlanClassesNoPrepList = coursePlanClassesNativeRepository.findByCourseDateAndClassesIdAndCategoryOrderByBeginTimeDesc(DateUtil.parseToDay(lessonDayStr), classesId, instructionRecord.getCategory());
                if (coursePlanClassesNoPrepList.size() > 0) {
                    coursePlanClassesRepository.deleteAll(coursePlanClassesNoPrepList);
                }

                //判断当天主题课程是否有主题课程未排课
                for (int k = 0; k < coursePlanTopicList.size(); k++) {

                    String topicBeginTime = DateUtil.formatDateToHmsStr(coursePlanTopicList.get(k).getBeginTime());
                    if (instructionRecord.getBeginDate().toString().equals(topicBeginTime)) {
                        CoursePlanClasses coursePlanClasses = new CoursePlanClasses();
                        CoursePlanTopic coursePlanTopic = coursePlanTopicList.get(k);

                        coursePlanClasses.setAreaId(classes.getAreaId());
                        coursePlanClasses.setBeginCourseTeacherId("");
                        coursePlanClasses.setBeginCourseTime(null);
                        coursePlanClasses.setBeginTime(coursePlanTopic.getBeginTime());
                        if (coursePlanTopic.getCourseType() == 1) {
                            coursePlanClasses.setCategory(2);//sat课程
                        } else if (coursePlanTopic.getCourseType() == 2) {
                            coursePlanClasses.setCategory(3);//园区自建
                        } else if (coursePlanTopic.getCourseType() == 3) {
                            coursePlanClasses.setCategory(1);//主题课程
                        }
                        //CourseConstant.Category.NURSERY.codeOf();
                        coursePlanClasses.setClassesId(classesId);
                        coursePlanClasses.setCourseDate(coursePlanTopic.getCourseDate());
                        coursePlanClasses.setCourseId(coursePlanTopic.getCourseId());
                        coursePlanClasses.setCourseName(coursePlanTopic.getCourseName());
                        coursePlanClasses.setCoursePlanTopicId(coursePlanTopic.getId());
                        coursePlanClasses.setCourseStatus(0);
                        coursePlanClasses.setCourseType(coursePlanTopic.getCourseType());
                         coursePlanClasses.setEndTime(coursePlanTopic.getEndTime());
                        coursePlanClasses.setPrepareStatus(0);
                        coursePlanClasses.setTypeName(coursePlanTopic.getTypeName());

                        CoursePlanClasses newCoursePlanClasses = coursePlanClassesRepository.save(coursePlanClasses);

                        System.out.println("--------------" + newCoursePlanClasses.getId());

                        nurseryScheduleRecord.setActivityContent(coursePlanTopic.getCourseName());
                        nurseryScheduleRecord.setResObj(coursePlanTopic.getCourseId());
                        nurseryScheduleList.add(nurseryScheduleRecord);
                        //TODO: 新增课程观测点
                    }
                }
            } else if(instructionRecord.getCategory() == 0){ //活动课
                if (instructionRecord.getIsResObj() == 0) {  //判断是否需要获取一日指导资源信息(0:不获取 1：获取)
                    nurseryScheduleRecord.setActivityContent(nurseryInstructionRecord.get(i).getActivityContent());
                    nurseryScheduleRecord.setResObj(nurseryInstructionRecord.get(i).getResObj());
                    nurseryScheduleList.add(nurseryScheduleRecord);
                }
            }
        }

        //保存托班一日记录
        nurseryScheduleRecordRepository.saveAll(nurseryScheduleList);

        return nurserySchedule;
    }

	@Override
	public List<InstructionResourceRecordVo> getInstructionRescourceByClassesId(String classesId,String lessonDate,Integer type) {
		  //通过班级ID获取班级信息
        Classes classes = classesRepository.getOne(classesId);
        //计算入园月龄
        LocalDate currentDate = LocalDate.parse(lessonDate).plusMonths(classes.getBeginMonth());
        LocalDate createdDate = LocalDate.parse( DateUtil.convertStr(classes.getCreated()));
        Integer diffMonth = Period.between(createdDate,currentDate).getMonths();
		//获取系统一日指导内容(资源信息)
        List<Object[]> instractionResourceRecordList = nurseryInstrationRecordRepository.findInstructionResourceRecordVoByMonthAndType(diffMonth, type);
        List<InstructionResourceRecordVo> voList = Lists.newArrayList();
        instractionResourceRecordList.forEach(o -> {
            voList.add(InstructionResourceRecordVo.of(o));
        });
		return voList;
	}

	@Override
	public List<NurseryClassesVo> scheduleLeaderClassesList(String areaId) {
		List<NurseryClassesVo> list = nurseryScheduleNativeRepository.findByAreaId(areaId);
        return list;
	}

    @Override
    public String exportExcel(String areaId, String staffId, String classesId, String courseDateStr){
        if (StringUtils.isBlank(classesId))
            throw new BusinessException(ErrorCode.CLASSES_IS_BLANK,"老师没有对应的的班级");

        Classes classes = classesRepository.findFirstByAreaIdAndIdAndDeletedIsFalse(areaId, classesId);
        if (classes == null){
            throw new BusinessException(ErrorCode.CLASSES_NOT_EXIST,"指定Id的对象不存在");
        }

        //处理数据
        List<NurseryScheduleDetailVo> weekNurseryScheduleList = new ArrayList<>();
        String monday = courseDateStr;
        List<String> weekDays = getWeekDays(monday);

        for(String day : weekDays){
            NurseryScheduleDetailVo nurseryScheduleDetailVo = scheduleTeacherDetail(classesId, day);

            if (nurseryScheduleDetailVo == null){
                nurseryScheduleDetailVo = new NurseryScheduleDetailVo();
            }
            nurseryScheduleDetailVo.setLessonDate(DateUtil.parseToDate(day));


            weekNurseryScheduleList.add(nurseryScheduleDetailVo);
        }

        long totalSize = weekNurseryScheduleList.stream().mapToInt(v -> v.getNurseryScheduleRecordList().size()).sum();
        if(totalSize == 0){
            throw new BusinessException("88888888","没有可导出数据",null);
        }

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("托班一日生活");

        Map<String,Object> cache = new HashMap<>();
        int totalDays = weekNurseryScheduleList.size();

        //表头
        String classesName = classes.getName();
        Date begin = weekNurseryScheduleList.get(0).getLessonDate();
        Date end = weekNurseryScheduleList.get(weekNurseryScheduleList.size() - 1).getLessonDate();
        String headTitle = classesName + "(" + new DateTime(begin).toString("yyyy-MM-dd") +" ~ "+ new DateTime(end).toString("yyyy-MM-dd") + ")";

        //第一行 班级名称
        createRowIndex0(workbook, sheet, headTitle);

        //第二行第一格 节次/课程/星期
        createRowIndex1(workbook, sheet);

        boolean rowheadLayouted = false;
        for (int i = 0; i < totalDays; i++){
            NurseryScheduleDetailVo vo = weekNurseryScheduleList.get(i);
            List<NurseryScheduleRecord> recordList = vo.getNurseryScheduleRecordList();

            DateTime date = new DateTime(vo.getLessonDate());
            String week = getWeekCN(date.getDayOfWeek());

            String dateFormat = week + "\n(" + date.toString("MM月dd日") + ")";

            //第一列上午下午节次
            if (recordList != null && recordList.size() > 0 && !rowheadLayouted) {
                //有课程时，依据第一个有课程的weekday数据区分上下午
                createNoonCol1(workbook, sheet, cache, recordList);
                rowheadLayouted = true;
            }

            int forceCol = i + 2;
            //日期数据
            createRowIndex1Date(workbook, sheet, forceCol, dateFormat);

            //课程内容
            createRowIndexI(workbook, sheet, forceCol, recordList);
        }

        mergedCellAndRow(sheet, cache);

        sheet.setDefaultColumnWidth(17);
        sheet.setDefaultRowHeight((short) (5 * 160));
        sheet.setHorizontallyCenter(true);
        sheet.setVerticallyCenter(true);

        sheet.setColumnWidth(0,10 * 220);
        sheet.setColumnWidth(1,10 * 220);
        sheet.setColumnWidth(2,40 * 180);
        sheet.setColumnWidth(3,40 * 180);
        sheet.setColumnWidth(4,40 * 180);
        sheet.setColumnWidth(5,40 * 180);
        sheet.setColumnWidth(6,40 * 180);
        sheet.setColumnWidth(7,40 * 180);
        sheet.setColumnWidth(8,40 * 180);
        sheet.setColumnWidth(9,40 * 180);

        String uploadedResult = null;
        try {
            String uploadCourseName = classesId +"_" + headTitle;
            String uploadPath = "teach/file/course_export_excel/" + DateTime.now().toString("yyyy-MM") + "/" + uploadCourseName + ".xls";

            String tempFileName = UUID.randomUUID().toString();
            File outputTempFile = File.createTempFile(tempFileName,".xls");
            FileOutputStream fileOutputStream = new FileOutputStream(outputTempFile);

            workbook.write(fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();

            String relativePath = ossProcessService.aliyunOssUpload(uploadPath, outputTempFile);

            uploadedResult = IMG_SERVICE_PREFIX + relativePath;

            outputTempFile.deleteOnExit();
            outputTempFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return uploadedResult;
    }

    private static String getWeekCN(int week){
        switch (week){
            case 1: return "星期一";
            case 2: return "星期二";
            case 3: return "星期三";
            case 4: return "星期四";
            case 5: return "星期五";
            case 6: return "星期六";
            case 7: return "星期天";
        }
        return "星期一";
    }

    private static void mergedCellAndRow(HSSFSheet sheet, Map<String, Object> cache) {
        HSSFRow row1 = sheet.getRow(1);
        int row1LastCellNum = row1.getLastCellNum();
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,row1LastCellNum - 1)); //合并第一行班级名称的单元格
        sheet.addMergedRegion(new CellRangeAddress(1,1,0,1)); //合并第二行 节次/课程/星期的单元格

        HSSFRow afterRow = (HSSFRow) cache.get("afterRow");
        if(Objects.nonNull(afterRow)){
            int lastRowNum = afterRow.getRowNum() > 2 ? afterRow.getRowNum() - 1 : afterRow.getRowNum();
            sheet.addMergedRegion(new CellRangeAddress(2,lastRowNum,0,0)); //合并上午课程内容行
            sheet.addMergedRegion(new CellRangeAddress(afterRow.getRowNum(),sheet.getLastRowNum(),0,0)); //合并下午课程内容行
        }else{
            //没有下午的课程
            int lastRowNum = sheet.getLastRowNum();
            sheet.addMergedRegion(new CellRangeAddress(2,lastRowNum,0,0)); //合并上午课程内容行
        }
    }

    private static void createNoonCol1(HSSFWorkbook workbook, HSSFSheet sheet, Map<String, Object> cache, List<NurseryScheduleRecord> recordVoList) {
        int contentRowSize = recordVoList.size();
        for(int i = 0 ; i < contentRowSize; i++){
            NurseryScheduleRecord record = recordVoList.get(i);
            DateTime endDate = new DateTime(record.getEndDate().getTime());
            int hour = endDate.getHourOfDay();

            //上午表格
            HSSFRow rowi = sheet.createRow(2 + i);
            {
                HSSFCell rowiCell0 = rowi.createCell(0);
                HSSFCell rowiCell1 = rowi.createCell(1);

                //下午时间在当前行建立一个下午的单元格,并保存当前行
                if(hour > 12) {
                    rowiCell0.setCellValue("下午");
                    if(!cache.containsKey("afterRow")){
                        cache.put("afterRow",rowi);
                    }
                }else{
                    rowiCell0.setCellValue("上午");
                }

                rowiCell1.setCellValue(i + 1);

                HSSFCellStyle cellStyle = workbook.createCellStyle();
                HSSFCellStyle cellStyle1 = workbook.createCellStyle();

                PoiUtils.setupCellTableHead(cellStyle);
                PoiUtils.setupCellTableStyle(cellStyle);

                PoiUtils.setupCellTableStyle(cellStyle1);

                rowiCell1.setCellStyle(cellStyle);
                rowiCell0.setCellStyle(cellStyle1);
            }

        }
    }

    private static void createRowIndexI(HSSFWorkbook workbook, HSSFSheet sheet, int forceCol, List<NurseryScheduleRecord> recordVoList) {
        if (recordVoList == null || recordVoList.size() == 0){
            return;
        }

        int contentRowSize = 12; //recordVoList.size();
        for(int i = 0 ; i < contentRowSize; i++){


            int row = 2 + i;
            HSSFRow rowi = sheet.getRow(row);
            if (rowi == null){
                rowi = sheet.createRow(row);
            }

            HSSFCell cell = rowi.getCell(forceCol);
            if (cell == null){
                cell = rowi.createCell(forceCol);
            }

            if (recordVoList != null && i < recordVoList.size()) {
                NurseryScheduleRecord record = recordVoList.get(i);
                String content = buildRowICellValue(record);
//            String content = String.format("%s\n%d::%d",attach, forceCol, row);
                cell.setCellValue(content);
            }else{
                cell.setCellValue("/");
            }

            HSSFCellStyle cellStyle = workbook.createCellStyle();
            PoiUtils.setupCellTableStyle(cellStyle);

            cellStyle.setWrapText(true);

            cell.setCellStyle(cellStyle);
        }
    }

    private static String buildRowICellValue(NurseryScheduleRecord record) {
        String content = record.getBegin() + "-" + record.getEnd() + "\n" + record.getActivityContent();
        content = content.replace("(", "\n(");

//        if (StringUtils.isNotBlank(record.getRemark())) {
//            return (content + "\n" + record.getRemark());
//        }
        return content;
    }

    private static void createRowIndex1Date(HSSFWorkbook workbook, HSSFSheet sheet, int forceCol, String date) {
        HSSFRow row1 = sheet.getRow(1);

        HSSFCellStyle style = workbook.createCellStyle();

        PoiUtils.setupCellTableStyle(style);

        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);

        font.setBold(true);
        font.setFontName("宋体");

        style.setFont(font);

        HSSFCell row1DateCell = row1.createCell(forceCol);

        row1DateCell.setCellStyle(style);
        row1DateCell.setCellValue(date);

    }

    private static void createRowIndex1(HSSFWorkbook workbook, HSSFSheet sheet) {
        HSSFRow row1 = sheet.getRow(1);
        if (row1 == null) {
            row1 = sheet.createRow(1);
        }
        row1.setHeight((short) (4 * 256));
        HSSFCell row1Cell0 = row1.createCell(0);
        row1Cell0.setCellValue("节次/课程/星期");

        HSSFCellStyle cellStyle = workbook.createCellStyle();
        PoiUtils.setupCellTableStyle(cellStyle);

        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);

        font.setBold(true);
        font.setFontName("宋体");

        cellStyle.setFont(font);
        row1Cell0.setCellStyle(cellStyle);
    }

    private static void createRowIndex0(HSSFWorkbook workbook, HSSFSheet sheet, String className) {

        int lastRowNum = sheet.getLastRowNum();
        if (lastRowNum == -1) {
            HSSFRow row0 = sheet.createRow(0);
            row0.setHeight((short) (4 * 256));
            HSSFCell row0Cell0 = row0.createCell(0);
            row0Cell0.setCellValue(className);

            HSSFCellStyle cellStyle = workbook.createCellStyle();
            PoiUtils.setupCellTableHead(cellStyle);
            PoiUtils.setupCellTableStyle(cellStyle);

            HSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short) 25);

            font.setBold(true);
            font.setFontName("宋体");

            cellStyle.setFont(font);
            row0Cell0.setCellStyle(cellStyle);
        }
    }

    private static List<String> getWeekDays(String monday){
        int days = 7;
        List<String> weekDays = new ArrayList<>();
        weekDays.add(monday);
        for (int i = 1; i < days ; i++){
            DateTime nextDay = DateTime.parse(monday).plusDays(i);
            weekDays.add(nextDay.toString("yyyy-MM-dd"));
        }
        return weekDays;
    }


    @Override
    public List<Children> door2DoorChildren(String areaId, String teacherId, String childrenName) {
        List<NurserySchedule> schedules = null;

        if (StringUtils.isNotEmpty(teacherId)) {
            schedules = nurseryScheduleRepository.findAllByAreaIdAndTeacherId(areaId, teacherId);
        }else{
            schedules = nurseryScheduleRepository.findAllByAreaIdAndTeacherIdIsNull(areaId);
        }

        String[] cids = schedules.stream().map(o->o.getChildrenId()).toArray(String[]::new);

        List<Children> childrenList = childrenRepository.findAllByAreaIdAndIdIn(areaId, cids);

        return childrenList;
    }
}
